(function ($) {
    Drupal.behaviors.autoBackTop = {
      attach: function (context, settings) {
        this.init();
        if (!$('#back-top').length) {
          return;
        }
        var scroll_timer;
        var displayed = false;
        var $message = $('#back-top');
        var $window = $(window);
        var top = $(document.body).children(0).position().top;
        $window.scroll(function () {
            window.clearTimeout(scroll_timer);
            scroll_timer = window.setTimeout(function () {
                if ($window.scrollTop() <= top) {
                    displayed = false;
                    $message.fadeOut(500);
                } else if (displayed == false) {
                    displayed = true;
                    $message.stop(true, true).show().click(function () {
                        $message.fadeOut(500);
                        $('html, body').animate({scrollTop:0},'slow');
                        return false;
                    });
                }
            }, 100);
        });

      },
      init: function() {
        if (!$('#back-top').length) {
          if(Drupal.settings.backtop) {
            $("body").append(Drupal.settings.backtop);
          }
        }
      }
    };
})(jQuery);
